<template>
  <div>
    <el-table :data="list" :loading="loading" class="mt20" style="width: 100%">
      <el-table-column label="姓名" prop="username" width="160px"></el-table-column>
      <el-table-column label="接收者账号" prop="phonenumber" width="160px">
        <template #default="{ row }">
          <span>{{ row.member && row.member.phonenumber ? row.member.phonenumber : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发送人" prop="senderUsername" width="100px"></el-table-column>
      <el-table-column label="有效期" prop="date" width="300px">
        <template #default="{ row }">
          <span v-if="row.startDate === 0">永久</span>
          <span v-else>{{ parseTime(row.startDate) }} ~ {{ parseTime(row.endDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" prop="createTime" width="160px">
        <template #default="{ row }">{{ parseTime(row.date) }}</template>
      </el-table-column>
      <el-table-column label="状态" prop="electricQuantityUpdateDate" width="100px">
        <template #default="{ row }">
          <span>{{ row.keyStatusName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250px">
        <template #default="{ row }">
          <div class="flex-row-center">
<!--            <el-button link type="primary" @click="handleSendMsg(row)">短信通知</el-button>-->
<!--            <el-button link type="primary">修改有效期</el-button>-->
            <el-dropdown trigger="click" placement="bottom-start" @command="moreCommand($event, row)">
              <el-button link type="primary" class="ml10">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="freeze">冻结</el-dropdown-item>
                  <el-dropdown-item command="remove">删除</el-dropdown-item>
<!--                  <el-dropdown-item command="record">操作记录</el-dropdown-item>-->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog v-model="sendKeyVisible" title="发送钥匙">
      <div>
        <span>803</span>
        <span>有效期：2024/03/17 20:29 - 2031/03/17 23:59</span>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSendMessage">发送短信</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="sendMessageVisible" title="发送短信">
      <el-form :model="msgForm" ref="msgFormRef">
        <el-form-item prop="account" label="手机号">
          {{ msgForm.account }}
        </el-form-item>
        <el-form-item prop="templateId" label="请选择模板" :rules="[{ required: true, message: '请选择模板', trigger: 'blur'}]">
          <el-select v-model="msgForm.templateId" placeholder="请选择模板">
            <el-option label="短信模板" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="params" label="预览">
          <el-input type="textarea" v-model="msgForm.params" :rows="5" disabled></el-input>
          <span>预计产生短信条数：3</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleMessageOk">
            发送
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="KeyPane">
import { useRouter } from 'vue-router'
import LockApi from "@/api/device/lock.js";
import { watch } from 'vue'

const { proxy } = getCurrentInstance()
const router = useRouter()

const loading = ref(false)
const total = ref(0)
const list = ref([])
const sendKeyVisible = ref(false)
const sendMessageVisible = ref(false)
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  msgForm: {
    account: undefined,
    templateId: undefined,
    params: undefined
  }
})

const props = defineProps({
  lockId: String
})

const { queryParams, msgForm } = toRefs(data)

const pageNum = ref(1)
const pageSize = ref(10)

function moreCommand(key, row) {
  switch(key) {
    case 'freeze':
      handleFreeze()
      break
    case 'remove':
      handleRemove()
      break
    case 'record':
      handleRecord()
      break
    default:
      break
  }
}

/* 冻结电子钥匙 */
function handleFreeze() {
  proxy.$modal.confirm("确定冻结电子钥匙？").then(() => {
    console.log('冻结');
  }).catch(() => {
    console.log('cancel');
  })
}
/* 删除电子钥匙 */
function handleRemove() {
  proxy.$modal.confirm("确定删除电子钥匙？").then(() => {
    console.log('删除');
  }).catch(() => {
    console.log('cancel');
  })
}

/* 使用记录 */
function handleRecord() {
  router.push({ path: '/deviceManagement/smartLock/record' })
}

/* 短信通知 */
function handleSendMsg() {
  sendKeyVisible.value = true
}
function handleSendMessage() {
  sendKeyVisible.value = false
  msgForm.value = {
    account: "13023123123",
    templateId: '1',
    params: '"您好，您的开门密码：","输入密码后，按键盘#号键开锁，《无线WIFI密码jy15880500888》"'
  }
  // msgForm.value.account = "13023123123"
  // msgForm.value.templateId = "1"
  // msgForm.value.params = '"您好，您的开门密码：","输入密码后，按键盘#号键开锁，《无线WIFI密码jy15880500888》"'
  sendMessageVisible.value = true
}
function handleMessageOk() {
  proxy.$refs['msgFormRef'].validate(valid => {
    if (valid) {
      sendMessageVisible.value = false
    }
  })
}

function getList() {
  if (!props.lockId) {
    return
  }
  
  loading.value = true
  const params = {
    ...queryParams.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  LockApi.getKeyList(props.lockId, params).then(res => {
    if (res.code === 200) {
      list.value = res.rows
      total.value = res.total
    }
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

function handleCurrentChange(val) {
  pageNum.value = val
  getList()
}

function handleSearch(params) {
  pageNum.value = 1
  queryParams.value = {
    ...queryParams.value,
    ...params
  }
  getList()
}

// 监听lockId变化，确保当lockId存在时加载数据
watch(() => props.lockId, (newVal) => {
  if (newVal) {
    getList()
  } else {
    list.value = []
    total.value = 0
  }
})

getList()
</script>
